package com.yisin.pbox.www.common.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;

import com.yisin.pbox.frame.util.FileUtils;
import com.yisin.pbox.frame.util.StringUtil;
import com.yisin.pbox.www.common.frame.BaseAction;

/**
 * @简述：<一句话介绍>
 * @详述：<详细介绍>
 * @author admin
 * @since 1.0
 */
public class FlexUploadAction extends BaseAction {

	private File file;
	private String fileName;
	private String saveFileName;
	private String type;
	private long fileMaxSize = 100 * 1024 * 1024;
	private String dirName = "users";

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	private String fileSavePath = "/";

	/**
	 * 设置文件保存路径
	 * 
	 * @param request
	 */
	public void setFileSavePath(HttpServletRequest request) {
		String spath = request.getRealPath("/");
		int index = spath.lastIndexOf("\\");
		fileSavePath = spath.substring(0, index + 1) + dirName + "/";
		fileSavePath = fileSavePath.replaceAll("\\\\", "/");
		FileUtils.createDir(fileSavePath);
	}

	/**
	 * 获取文件保存路径
	 * 
	 * @param request
	 */
	public String getFileSavePath() {
		return fileSavePath;
	}

	public void upload() {
		// 保存文件到服务器中
		PrintWriter pw = null;
		try {
			pw = response.getWriter();
			response.setContentType("text/html;charset=UTF-8");
			MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) ServletActionContext.getRequest();
			Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
			while (fileParameterNames != null && fileParameterNames.hasMoreElements()) {
				String inputName = (String) fileParameterNames.nextElement();

				String[] contentType = multiWrapper.getContentTypes(inputName);

				if (isNonEmpty(contentType)) {
					String[] fileNames = multiWrapper.getFileNames(inputName);
					if (isNonEmpty(fileNames)) {
						File[] files = multiWrapper.getFiles(inputName);
						if (files != null) {
							File file = null;
							for (int index = 0; index < files.length; index++) {
								file = files[index];
								float fileSize = StringUtil.stringToFloat(FileUtils.siSheWuRu((file.length() / (float) 1024)), 0f);
								System.out.println(user.getAccount() + " upload file...." + fileSize + "KB");
								setFileName(fileNames[index]);
								saveFileName = StringUtil.getUniqueId("f") + FileUtils.getFileZui(getFileName());
								String dir = FileUtils.getFileGenre(getFileName());
								dirName = "users/" + user.getAccount() + "/" + dir;
								setFileSavePath(request);
								boolean bool = false;
								if (type.equals("music")) {
									bool = addMusic();
								}
								if (bool) {
									copy(file, new File(getFileSavePath() + saveFileName));
									pw.write("Success.");
								} else {
									pw.write("Failed!");
								}
								pw.flush();
								pw.close();
							}
						}
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			pw.write("Failed!");
		}

	}

	public void outError(float csize, float msize, HttpServletResponse response) {
		try {
			PrintWriter pw = response.getWriter();
			pw.write("Exceeds the size limit!");
			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public boolean addMusic() {
		boolean bool = false;
		return bool;
	}

	public boolean isNonEmpty(Object[] objArray) {
		boolean result = false;
		for (int index = 0; index < objArray.length && !result; index++) {
			if (objArray[index] != null) {
				result = true;
			}
		}
		return result;
	}

	public void copy(File src, File dst) {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new BufferedInputStream(new FileInputStream(src), 1024);
			out = new BufferedOutputStream(new FileOutputStream(dst), 1024);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void setFileMaxSize(long fileMaxSize) {
		this.fileMaxSize = fileMaxSize;
	}

	public long getFileMaxSize() {
		return fileMaxSize;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

}
